<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Button, Card, Col, Empty, Row, Spin, message } from 'ant-design-vue';

import { getDashboardOverviewApi, type DashboardApi } from '#/api/core';

interface QuickLinkItem {
  label: string;
  description: string;
  routeName: string;
  type?: 'primary' | 'default';
}

const router = useRouter();
const loading = ref(false);
const overview = ref<DashboardApi.OverviewResponse | null>(null);

const quickLinks: QuickLinkItem[] = [
  {
    label: '发布任务',
    description: '快速创建用工任务',
    routeName: 'TaskPublish',
  },
  {
    label: '用工结算',
    description: '管理结算流程',
    routeName: 'BusinessSettlement',
  },
  {
    label: '申请开票',
    description: '提交开票申请',
    routeName: 'InvoiceManagement',
  },
  {
    label: '账单查询',
    description: '查看账户资金流水',
    routeName: 'TransactionBill',
  },
];

const formatCurrency = (value: number | string | undefined) => {
  const amount = Number(value ?? 0);
  if (Number.isNaN(amount)) {
    return '0.00';
  }
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(amount);
};

const assetCards = computed(() => {
  const tenant = overview.value?.tenant;
  return [
    {
      key: 'account_balance',
      title: '账户余额',
      value: `¥${formatCurrency(tenant?.account_balance)}`,
    },
    {
      key: 'invoiceable_amount',
      title: '可开票金额',
      value: `¥${formatCurrency(tenant?.invoiceable_amount)}`,
    },
  ];
});

const landingCompanies = computed(() => overview.value?.landing_companies ?? []);

const fetchOverview = async () => {
  loading.value = true;
  try {
    overview.value = await getDashboardOverviewApi();
  } catch (error) {
    console.error('获取首页概览失败', error);
    message.error('获取首页概览失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const handleQuickLink = (link: QuickLinkItem) => {
  router.push({ name: link.routeName }).catch(() => {
    message.error('页面跳转失败，请稍后重试');
  });
};

onMounted(() => {
  fetchOverview();
});
</script>

<template>
  <div class="dashboard-wrapper">
    <Card class="section-card" :bordered="false" title="资产概况">
      <Row :gutter="16">
        <Col v-for="card in assetCards" :key="card.key" :xs="24" :md="12" :lg="12">
          <Card class="asset-card" bordered>
            <div class="asset-card__title">{{ card.title }}</div>
            <div class="asset-card__value">{{ card.value }}</div>
          </Card>
        </Col>
      </Row>
    </Card>

    <Card class="section-card" :bordered="false" title="快捷入口">
      <Row :gutter="[16, 16]">
        <Col
          v-for="link in quickLinks"
          :key="link.routeName"
          :xs="24"
          :sm="12"
          :md="12"
          :lg="6"
          :xl="6"
        >
          <Button
            :type="link.type ?? 'default'"
            size="large"
            class="quick-link-button"
            @click="handleQuickLink(link)"
          >
            <div class="quick-link">
              <div class="quick-link__label">{{ link.label }}</div>
              <div class="quick-link__desc">{{ link.description }}</div>
            </div>
          </Button>
        </Col>
      </Row>
    </Card>

    <Card class="section-card" :bordered="false" title="落地公司">
      <Spin :spinning="loading">
        <template v-if="landingCompanies.length">
          <Row :gutter="16">
            <Col
              v-for="(company, index) in landingCompanies"
              :key="`${company.tax_number || company.account_number || index}`"
              :xs="24"
              :md="12"
              :lg="8"
              class="mb-4"
            >
              <Card class="landing-card" bordered>
                <div class="landing-card__name">{{ company.name }}</div>
                <ul class="landing-card__info">
                  <li>
                    <span class="label">税号</span>
                    <span class="value">{{ company.tax_number || '--' }}</span>
                  </li>
                  <li>
                    <span class="label">开户行</span>
                    <span class="value">{{ company.bank_name || '--' }}</span>
                  </li>
                  <li>
                    <span class="label">银行账号</span>
                    <span class="value">{{ company.account_number || '--' }}</span>
                  </li>
                  <li>
                    <span class="label">开票类目</span>
                    <span class="value">
                      {{ company.billing_categories?.length ? company.billing_categories.join('、') : '--' }}
                    </span>
                  </li>
                </ul>
              </Card>
            </Col>
          </Row>
        </template>
        <Empty v-else description="暂无落地公司数据" />
      </Spin>
    </Card>
  </div>
</template>

<style scoped>
.dashboard-wrapper {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
}

.section-card {
  border-radius: 12px;
}

.asset-card {
  border-radius: 12px;
  min-height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #eef2ff 100%);
}

.asset-card__title {
  font-size: 14px;
  color: #64748b;
}

.asset-card__value {
  margin-top: 14px;
  font-size: 28px;
  font-weight: 600;
  color: #1e293b;
}

.quick-link {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.quick-link-button {
  min-width: 170px;
  min-height: 68px;
  padding: 16px 24px !important;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  width: 100%;
}

.quick-link__label {
  font-size: 16px;
  font-weight: 600;
}

.quick-link__desc {
  font-size: 12px;
  color: #64748b;
}

.landing-card {
  border-radius: 12px;
  min-height: 100%;
}

.landing-card__name {
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 12px;
}

.landing-card__info {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.landing-card__info .label {
  display: inline-block;
  width: 80px;
  color: #6b7280;
  font-size: 13px;
}

.landing-card__info .value {
  color: #111827;
  font-size: 14px;
  word-break: break-all;
}

@media (max-width: 767px) {
  .dashboard-wrapper {
    padding: 16px;
  }

  .asset-card__value {
    font-size: 24px;
  }

  .quick-link-button {
    min-width: 140px;
    min-height: 64px;
    width: 100%;
    justify-content: center;
  }
}
</style>
